import 'package:efood_multivendor/controller/cart_controller.dart';
import 'package:efood_multivendor/controller/coupon_controller.dart';
import 'package:efood_multivendor/controller/restaurant_controller.dart';
import 'package:efood_multivendor/data/model/response/cart_model.dart';
import 'package:efood_multivendor/data/model/response/product_model.dart';
import 'package:efood_multivendor/helper/price_converter.dart';
import 'package:efood_multivendor/helper/route_helper.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/images.dart';
import 'package:efood_multivendor/view/screens/cart/widget/cart_widget.dart';
import 'package:efood_multivendor/view/screens/checkout/checkout_screen.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'custom_snackbar.dart';

class CartView extends StatefulWidget {
  final Widget cartChilds;
  final String price;
  final int? restaurantId;
  final int? productId;

  CartView(this.cartChilds, this.price, {this.restaurantId, this.productId});

  @override
  State<CartView> createState() => CartViewState();
}

class CartViewState extends State<CartView>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      animationBehavior: AnimationBehavior.preserve,
      vsync: this,
      duration: const Duration(milliseconds: 500),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CartController>(builder: (cartController) {
      return WillPopScope(
        onWillPop: () async {
          if (cartController.isCartOpen) {
            cartController.closeCart();
            return false;
          } else {
            return true;
          }
        },
        child: CartDialog(
          child: widget.cartChilds,
          price: widget.price,
          restaurantId: widget.restaurantId,
          productId: widget.productId,
        ),
      );
    });
  }

  void closeCart() {
    _controller.reverse();
  }
}

class CartDialog extends StatefulWidget {
  const CartDialog(
      {Key? key,
      required this.child,
      this.price,
      this.restaurantId,
      this.productId})
      : super(key: key);
  final Widget child;
  final String? price;
  final int? restaurantId;
  final int? productId;

  @override
  State<CartDialog> createState() => _CartDialogState();
}

class _CartDialogState extends State<CartDialog>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  CartController cartController = Get.find<CartController>();

  RestaurantController restController = Get.find<RestaurantController>();
  bool _expanded = false;
  double _addOnPrice = 0;
  @override
  void initState() {
    super.initState();

    _animationController = AnimationController(
      animationBehavior: AnimationBehavior.normal,
      vsync: this,
      duration: const Duration(milliseconds: 100),
    );
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return GetBuilder<CartController>(builder: (cartController) {
      return Material(
        child: Stack(
          children: <Widget>[
            widget.child,
            Positioned(
              bottom: 1.h,
              left: MediaQuery.of(context).size.width / 20,
              right: MediaQuery.of(context).size.width / 20,
              child: menu(context, size, cartController, price: widget.price),
            ),
            Positioned(
              left: size.width / 7,
              bottom: GetPlatform.isAndroid ? 5.h : size.height / 11,
              child: Container(
                width: size.width * 0.08,
                height: size.width * 0.08,
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                        colors: ((widget.restaurantId == null)
                                ? (cartController.cartList.isEmpty)
                                : ((cartController.cartRest.isEmpty)
                                    ? true
                                    : (cartController.cartRest
                                            .containsKey(widget.restaurantId))
                                        ? (cartController
                                            .cartRest[widget.restaurantId]!
                                            .isEmpty)
                                        : (true)))
                            ? [Colors.grey, Colors.white]
                            : [Color(0xffff8022), Color(0xffff2222)]),
                    borderRadius: BorderRadius.circular(100)),
                child: Center(
                  child: Text(
                    cartController
                        .getTotalQuantity(resId: widget.restaurantId)
                        .toString(),
                    style: const TextStyle(color: Colors.white, fontSize: 20),
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    });
  }

  SafeArea menu(BuildContext context, Size size, CartController cartController,
      {bool cartExpanded = false, String? price}) {
    List<bool> _availableList = [];
    double _itemPrice = 0;
    double _addOns = 0;

    if (widget.restaurantId != null) {
      if (cartController.cartRest.isNotEmpty) {
        if (cartController.cartRest.containsKey(widget.restaurantId)) {
          _addOnPrice = 0;
          List<AddOn> _addOnList = [];
          cartController.cartRest[widget.restaurantId]?.forEach((cartModel) {
            if (cartModel.product?.addOns?.isNotEmpty == true &&
                cartModel.addOnIds?.isNotEmpty == true) {
              if (cartModel.addOnIds?.isNotEmpty == true) {
                for (int index = 0;
                    index < cartModel.addOnIds!.length;
                    index++) {
                  _addOnPrice = _addOnPrice +
                      (cartModel.addOnIds![index].price! *
                          cartModel.addOnIds![index].quantity!);
                }
              }
            }
            _availableList.add(cartModel.product!.is_open!);

            _itemPrice = _itemPrice + (cartModel.price! * cartModel.quantity);
          });

          cartController.cartRest[widget.restaurantId]?.forEach((cartModel) {
            for (int i = 0; i < 1; i++) {
              if (cartController.cartRest.length >= 1) {
                if (cartModel.product?.addOns?.isNotEmpty == true &&
                    cartModel.addOnIds?.isNotEmpty == true) {
                  cartModel.addOnIds!.forEach((addOnId) {
                    for (int i = 0; i < 1; i++) {
                      for (AddOns addOns in cartModel.product!.addOns!) {
                        if (addOns.id == addOnId.id) {
                          if (cartController.cartRest.length > 1) {
                            if (_addOns == addOnId.price) {
                              _addOns = addOnId.price! * addOnId.quantity!;
                            }
                          } else {
                            if (cartController.cartRest.length > 1) {
                              if (_addOns == addOnId.price) {
                                _addOns = _addOns +
                                    addOnId.price! * addOnId.quantity!;
                              }
                            } else {
                              _addOns =
                                  _addOns + addOnId.price! * addOnId.quantity!;
                            }
                          }
                          if (cartController.cartRest.length > 1 && i == 0) {
                            cartController.totalAddonPrice(_addOns, 0,
                                cartModel.product!.id!, true, false);
                            break;
                          } else {
                            cartController.totalAddonPrice(_addOns, addOnId.id!,
                                cartModel.product!.id!, true, false);
                          }

                          break;
                        }
                      }
                      break;
                    }
                  });
                }
              }
            }
          });
        }
      }
    }

    double addonprice = _addOnPrice > 0
        ? _addOnPrice
        : cartController.cartRest.containsKey(widget.restaurantId) &&
                cartController.cartRest[widget.restaurantId]!.length > 0
            ? _addOnPrice
            : 0;
    double _subTotal = _itemPrice + addonprice;

    double _discount = 0;
    if (widget.restaurantId != null) {
      if (cartController.cartRest.isNotEmpty) {
        cartController.amtRest.forEach((key, value) {});
        if (cartController.cartRest.containsKey(widget.restaurantId)) {
          for (CartModel cartModel
              in cartController.cartRest[widget.restaurantId]!) {
            _discount += cartModel.discountAmount! * cartModel.quantity;
          }
        }
      }
    } else {
      for (CartModel cartModel in cartController.cartList) {
        _discount += cartModel.discountAmount! * cartModel.quantity;
      }
    }

    if (restController.restaurant != null &&
        restController.restaurant?.discount != null) {
      if (restController.restaurant?.discount!.maxDiscount != 0 &&
          restController.restaurant!.discount!.maxDiscount! < _discount) {
        _discount = restController.restaurant!.discount!.maxDiscount!;
      }
      if (restController.restaurant!.discount!.minPurchase != 0 &&
          restController.restaurant!.discount!.minPurchase! >
              (_subTotal + _addOns)) {
        _discount = 0;
      }
    }

    return SafeArea(
      child: Container(
          height: MediaQuery.of(context).size.height / 15,
          decoration: BoxDecoration(
            borderRadius:
                BorderRadius.circular(MediaQuery.of(context).size.width / 1),
            gradient: LinearGradient(
                colors: ((widget.restaurantId == null)
                        ? (cartController.cartList.isEmpty)
                        : ((cartController.cartRest.isEmpty)
                            ? true
                            : (cartController.cartRest
                                    .containsKey(widget.restaurantId))
                                ? (cartController
                                    .cartRest[widget.restaurantId]!.isEmpty)
                                : (true)))
                    ? [Colors.grey, Colors.white]
                    : [Color(0xffff8022), Color(0xffff2222)]),
            boxShadow: [
              BoxShadow(
                color: ((widget.restaurantId == null)
                        ? cartController.cartList.isEmpty
                        : ((cartController.cartRest.isEmpty)
                            ? true
                            : (cartController.cartRest
                                    .containsKey(widget.restaurantId))
                                ? (cartController
                                    .cartRest[widget.restaurantId]!.isEmpty)
                                : (true)))
                    ? Colors.grey
                    : Color(0xffff2222).withOpacity(0.8),
                blurRadius: 12,
                spreadRadius: 2,
              )
            ],
          ),
          child: GestureDetector(
            onTap: () {
              if ((widget.restaurantId == null)
                  ? cartController.cartList.length > 0
                  : ((cartController.cartRest.isEmpty)
                      ? false
                      : (cartController.cartRest
                              .containsKey(widget.restaurantId))
                          ? (cartController
                                  .cartRest[widget.restaurantId]!.length >
                              0)
                          : (false))) {
                setState(() {
                  _animationController.forward();
                  if (cartController.isCartOpen) {
                    cartController.closeCart();
                    Get.back();
                  } else {
                    _animationController.reverse();
                    cartController.openCart();
                    showDialog(context, widget.price!);
                  }
                });
              }
            },
            child: Center(
              child: Padding(
                padding: const EdgeInsets.only(left: 5, right: 5),
                child: Row(
                  children: [
                    InkWell(
                      onTap: () {
                        if ((widget.restaurantId == null)
                            ? cartController.cartList.length > 0
                            : ((cartController.cartRest.isEmpty)
                                ? false
                                : (cartController.cartRest
                                        .containsKey(widget.restaurantId))
                                    ? (cartController
                                            .cartRest[widget.restaurantId]!
                                            .length >
                                        0)
                                    : (false))) {
                          setState(() {
                            if (cartController.isCartOpen) {
                              cartController.closeCart();
                              Get.back();
                            } else {
                              cartController.openCart();
                              showDialog(context, widget.price!);
                            }
                          });
                        }
                      },
                      child: Stack(
                        children: [
                          Container(
                            width: size.width * 0.12,
                            height: size.width * 0.12,
                            decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(100)),
                          ),
                          Positioned(
                            top: MediaQuery.of(context).size.height / 110,
                            left: MediaQuery.of(context).size.width / 60,
                            child: ShaderMask(
                              shaderCallback: (shade) {
                                return LinearGradient(
                                  colors: ((widget.restaurantId == null)
                                          ? cartController.cartList.isEmpty
                                          : ((cartController.cartRest.isEmpty)
                                              ? true
                                              : (cartController.cartRest
                                                      .containsKey(
                                                          widget.restaurantId))
                                                  ? (cartController
                                                      .cartRest[
                                                          widget.restaurantId]!
                                                      .isEmpty)
                                                  : (true)))
                                      ? [
                                          Colors.grey,
                                          Colors.grey,
                                        ]
                                      : [Color(0xffff8022), Color(0xffff2222)],
                                  tileMode: TileMode.mirror,
                                ).createShader(shade);
                              },
                              child: SizedBox(
                                  width: size.width * 0.08,
                                  height: size.width * 0.08,
                                  child: ((widget.restaurantId == null)
                                          ? cartController.cartList.isEmpty
                                          : ((cartController.cartRest.isEmpty)
                                              ? true
                                              : (cartController.cartRest
                                                      .containsKey(
                                                          widget.restaurantId))
                                                  ? (cartController
                                                      .cartRest[
                                                          widget.restaurantId]!
                                                      .isEmpty)
                                                  : (true)))
                                      ? Image.asset(
                                          Images.cart,
                                          color: Color.fromARGB(
                                              255, 158, 158, 158),
                                        )
                                      : Image.asset(
                                          Images.cart,
                                        )),
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(
                      width: 20,
                    ),
                    FittedBox(
                      fit: BoxFit.scaleDown,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            ((widget.restaurantId == null)
                                    ? "${PriceConverter.convertPrice(cartController.amount - _discount)}"
                                    : ((cartController.cartRest.isEmpty)
                                        ? "${PriceConverter.convertPrice(0)}"
                                        : (cartController.amtRest.containsKey(
                                                widget.restaurantId))
                                            ? "${PriceConverter.convertPrice(_subTotal - _discount)}"
                                            : "${PriceConverter.convertPrice(0)}"))
                                .tr,
                            style: const TextStyle(
                                fontSize: 18,
                                color: Colors.white,
                                fontWeight: FontWeight.bold),
                          ),
                          ((widget.restaurantId == null)
                                  ? cartController.cartList.isEmpty
                                  : ((cartController.cartRest.isEmpty)
                                      ? true
                                      : (cartController.cartRest
                                              .containsKey(widget.restaurantId))
                                          ? (cartController
                                              .cartRest[widget.restaurantId]!
                                              .isEmpty)
                                          : (true)))
                              ? SizedBox()
                              : Text(
                                  price!.isEmpty || price == 'null'
                                      ? "+" + " " + "${"deliv_fee".tr}"
                                      : "+" +
                                          "$price ${"birr".tr} ${"deliv_fee".tr}",
                                  style: const TextStyle(
                                      fontSize: 14,
                                      color: Colors.white,
                                      fontWeight: FontWeight.w300),
                                )
                        ],
                      ),
                    ),
                    const Spacer(),
                    GestureDetector(
                      onTap: () {
                        List itemIds = [];
                        List itemNames = [];
                        List categories = [];

                        if ((widget.restaurantId == null)
                            ? cartController.cartList.length > 0
                            : ((cartController.cartRest.isEmpty)
                                ? false
                                : (cartController.cartRest
                                        .containsKey(widget.restaurantId))
                                    ? (cartController
                                            .cartRest[widget.restaurantId]!
                                            .length >
                                        0)
                                    : (false))) {
                          List<CartModel> _cartList = (widget.restaurantId !=
                                  null)
                              ? cartController.cartRest[widget.restaurantId]!
                              : cartController.cartList;
                          for (int index = 0;
                              index < _cartList.length;
                              index++) {
                            itemIds.add(_cartList[index].product!.id);
                            itemNames.add(_cartList[index].product!.name);
                            categories
                                .add(_cartList[index].product!.categoryId);
                          }
                        }
                        if ((widget.restaurantId == null)
                            ? cartController.cartList.length > 0
                            : ((cartController.cartRest.length < 0)
                                ? false
                                : (cartController.cartRest
                                        .containsKey(widget.restaurantId))
                                    ? (cartController
                                            .cartRest[widget.restaurantId]!
                                            .length >
                                        0)
                                    : (false))) {
                          if (cartController.isCartOpen) {
                            cartController.closeCart();
                            Get.back();
                          }
                          if (_availableList.contains(false)) {
                            showCustomSnackBar(
                                'one_or_more_product_unavailable'.tr);
                          } else {
                            Get.find<CouponController>()
                                .removeCouponData(false);
                            cartController.closeCart();
                            Get.toNamed(RouteHelper.getCheckoutRoute('cart'),
                                arguments: CheckoutScreen(
                                  fromCart: true,
                                  cartList: ((widget.restaurantId != null)
                                      ? cartController
                                          .cartRest[widget.restaurantId]!
                                      : cartController.cartList),
                                  restaurantID: widget.restaurantId,
                                ));
                          }
                        }
                      },
                      child: Container(
                        width: size.width * 0.3,
                        height: size.width * 0.12,
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(100)),
                        child: Center(
                          child: ShaderMask(
                            shaderCallback: (shade) {
                              return LinearGradient(
                                colors: ((widget.restaurantId == null)
                                        ? cartController.cartList.isEmpty
                                        : ((cartController.cartRest.isEmpty)
                                            ? true
                                            : (cartController.cartRest
                                                    .containsKey(
                                                        widget.restaurantId))
                                                ? (cartController
                                                    .cartRest[
                                                        widget.restaurantId]!
                                                    .isEmpty)
                                                : (true)))
                                    ? [
                                        Color.fromARGB(255, 194, 194, 194),
                                        Color.fromARGB(255, 125, 125, 125),
                                      ]
                                    : [Color(0xffff8022), Color(0xffff2222)],
                                tileMode: TileMode.mirror,
                              ).createShader(shade);
                            },
                            child: Text(
                              "buy_now".tr,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
          )),
    );
  }

  void showDialog(BuildContext context, String price) {
    List<CartModel>? _cartList = (widget.restaurantId != null)
        ? cartController.cartRest[widget.restaurantId]
        : cartController.cartList;
    final size = MediaQuery.of(context).size;
    showGeneralDialog(
      barrierLabel: "Barrier",
      barrierDismissible: true,
      transitionDuration: const Duration(milliseconds: 100),
      context: context,
      pageBuilder: (_, __, ___) {
        return StatefulBuilder(builder: (context, setState) {
          return GetBuilder<CartController>(builder: (cartController) {
            return Padding(
              padding: EdgeInsets.only(bottom: 1.h),
              child: Material(
                type: MaterialType.transparency,
                shape: const RoundedRectangleBorder(
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(15),
                        topRight: Radius.circular(15),
                        bottomLeft: Radius.circular(70),
                        bottomRight: Radius.circular(70))),
                child: SafeArea(
                  child: Padding(
                    padding: EdgeInsets.only(
                      left: MediaQuery.of(context).size.width / 20,
                      right: MediaQuery.of(context).size.width / 20,
                    ),
                    child: Stack(
                      children: [
                        Align(
                          alignment:
                              Alignment.bottomCenter.add(Alignment(0, -0.1)),
                          child: Container(
                            constraints: BoxConstraints(
                                maxHeight:
                                    MediaQuery.of(context).size.height / 3),
                            decoration: const BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(15),
                                    topRight: Radius.circular(15),
                                    bottomLeft: Radius.circular(5),
                                    bottomRight: Radius.circular(5))),
                            child: ListView.builder(
                                itemCount: (_cartList?.length ?? 0) + 1,
                                shrinkWrap: true,
                                itemBuilder: (ctx, index) {
                                  return index != _cartList?.length
                                      ? CartListItem(
                                          index: cartController.getIndex(
                                              _cartList![index].product),
                                          fromRes: (widget.restaurantId != null
                                              ? true
                                              : false),
                                        )
                                      : SizedBox(
                                          height: 8.h,
                                        );
                                }),
                          ),
                        ),
                        Align(
                            alignment: Alignment.bottomCenter,
                            child: menu(context, size, cartController,
                                cartExpanded: true, price: price))
                      ],
                    ),
                  ),
                ),
              ),
            );
          });
        });
      },
      transitionBuilder: (_, anim, __, child) {
        return SlideTransition(
          position: Tween(begin: const Offset(0, 0.2), end: const Offset(0, 0))
              .animate(anim.drive(CurveTween(curve: Curves.elasticInOut))),
          child: child,
        );
      },
    ).then((value) {
      _animationController.reverse();
      cartController.closeCart();
    });
  }
}
